package com.hifar.test.sensor.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.fw.utils.id.IdUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.log.AutoLogUtils;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.*;
import com.hifar.test.equipsensor.pojo.HfResEquipSensor;
import com.hifar.test.equipsensor.service.IHfResEquipSensorService;
import com.hifar.test.sensor.pojo.HfResSensor;
import com.hifar.test.sensor.pojo.VO.EquipSensorQueryParamVO;
import com.hifar.test.sensor.service.IHfResSensorService;
import com.hifar.validate.CreateGroup;
import com.hifar.validate.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 传感器管理 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-11 11:58:47
 */
@RestController
@RequestMapping("/api/busi/test/hfResSensorController")
@Api(tags = "传感器管理功能")
public class HfResSensorController {

    @Autowired
    private IHfResSensorService hfResSensorService;

    @Autowired
    private IHfResEquipSensorService hfResEquipSensorService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @Autowired
    private AutoLogUtils autoLogUtils;


    @PostMapping(value = "/list")
    @ApiOperation(value = "传感器管理功能:分页查询列表")
    public BusiResponse list(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<HfResSensor> queryWrapper = RequestConver.getPostParam(pageInfo);

        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);

        String equipTypeCode = StringUtils.trimNull(pageInfo.get("equipTypeCode"), "");
        String searchType = StringUtils.trimNull(pageInfo.get("searchType"), "9");
        if (!"".equals(equipTypeCode)) {
            queryWrapper.eq("equip_type_code", equipTypeCode);

        }

        // 当天开始时间戳
        long tm = com.hifar.fw.utils.lang.DateUtils.getDayStartLong(System.currentTimeMillis());
        // 第8天开始
        long weekTime = tm + 7 * 24 * 60 * 60 * 1000L;
        // 第31天开始
        long monthTime = tm + 30 * 24 * 60 * 60 * 1000L;

        //1-过期数据 2-7天内过期 3-30天过期 4-有效设备 9-所有数据
        if ("9".equals(searchType)) {
        } else if ("1".equals(searchType)) {
            queryWrapper.gt("check_period_date", new Date(0));
            queryWrapper.lt("check_period_date", new Date(tm));
        } else if ("2".equals(searchType)) {
            queryWrapper.gt("check_period_date", new Date(tm));
            queryWrapper.lt("check_period_date", new Date(weekTime));
        } else if ("3".equals(searchType)) {
            queryWrapper.gt("check_period_date", new Date(tm));
            queryWrapper.lt("check_period_date", new Date(monthTime));
        } else if ("4".equals(searchType)) {
            queryWrapper.gt("check_period_date", new Date(tm));
        }

        queryWrapper.orderByAsc("row_sort");
        queryWrapper.orderByDesc("create_time");
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<HfResSensor> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<HfResSensor> pageData = hfResSensorService.page(page, queryWrapper);
            /* 计算分页信息返回给前端 */
            PageResult pageResult = SystemUtil.parsePage(page, pageData);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }


    @PostMapping(value = "/checkStatusCount")
    @ApiOperation(value = "资源-设备功能:统计鉴定有效状态")
    public BusiResponse countStatus(HttpServletRequest request) {
        QueryWrapper<HfResSensor> queryWrapper = new QueryWrapper<>();
        // 当天开始时间戳
        long tm = com.hifar.fw.utils.lang.DateUtils.getDayStartLong(System.currentTimeMillis());
        // 第8天开始
        long weekTime = tm + 7L * 24 * 60 * 60 * 1000;
        // 第31天开始
        long monthTime = tm + 30L * 24 * 60 * 60 * 1000;

        //1-过期数据 2-7天内过期 3-30天过期  4-有效设备  9-所有数据
        queryWrapper = new QueryWrapper<>();
        int all = hfResSensorService.count(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("check_period_date", new Date(0));
        queryWrapper.lt("check_period_date", new Date(tm));
        int expire = hfResSensorService.count(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("check_period_date", new Date(tm));
        int valid = hfResSensorService.count(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("check_period_date", new Date(tm));
        queryWrapper.lt("check_period_date", new Date(weekTime));
        int day7 = hfResSensorService.count(queryWrapper);

        queryWrapper.gt("check_period_date", new Date(tm));
        queryWrapper.lt("check_period_date", new Date(monthTime));
        int day30 = hfResSensorService.count(queryWrapper);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("all", all);
        retMap.put("expire", expire);
        retMap.put("valid", valid);
        retMap.put("day7", day7);
        retMap.put("day30", day30);

        if (retMap != null) {
            return BusiResponse.OK(retMap);
        } else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }


    @PostMapping(value = "/listByNotEquipId")
    @ApiOperation(value = "传感器管理功能:分页查询列表")
    public BusiResponse listByNotEquipId(@RequestBody EquipSensorQueryParamVO queryParamsVO) {
        QueryParamBean<HfResSensor> queryParamBean = new QueryParamBean<>(queryParamsVO, HfResSensor.class);
        QueryWrapper<HfResSensor> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfResSensor> page = queryParamBean.getPage();
        String equipId = queryParamsVO.getEquipId();

        String equipTypeCode = queryParamsVO.getEquipTypeCode();

        QueryWrapper<HfResEquipSensor> equipSensorQueryWrapper = new QueryWrapper<>();
        equipSensorQueryWrapper.lambda()
                .select(HfResEquipSensor::getSensorId)
                .eq(HfResEquipSensor::getEquipId, equipId);
        List<HfResEquipSensor> equipSensorList = hfResEquipSensorService.list(equipSensorQueryWrapper);
        List<String> sensorIdList = equipSensorList.stream()
                .map(HfResEquipSensor::getSensorId)
                .collect(Collectors.toList());
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (!sensorIdList.isEmpty()) {
            queryWrapper.notIn("id", sensorIdList);
        }
        queryWrapper.orderByAsc("row_sort");
        queryWrapper.orderByDesc("create_time");
        Page<HfResSensor> pageData = hfResSensorService.page(page, queryWrapper);
        /* 计算分页信息返回给前端 */
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @PostMapping(value = "/listAll")
    @ApiOperation(value = "传感器管理功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {

        QueryWrapper<HfResSensor> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        List<HfResSensor> list = hfResSensorService.list(queryWrapper);
        return BusiResponse.OK(list);
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "传感器管理功能:新增")
    public BusiResponse add(@RequestBody @Validated(CreateGroup.class) HfResSensor hfResSensor) {
        String id = IdUtils.uuid32();
        hfResSensor.setId(id);
        // 判断设备编号是否重复
        QueryWrapper<HfResSensor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(HfResSensor::getDelFlag, 1);
        String sensorCode = hfResSensor.getSensorCode();
        queryWrapper.eq("sensor_code", sensorCode);
        int count = hfResSensorService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("编码%s已经存在！", hfResSensor.getSensorCode()));
        }
        hfResSensorService.save(hfResSensor);

        autoLogUtils.addLog("环境试验-传感器台账", String.format("新增传感器:【%s】", sensorCode));
        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/edit")
    @ApiOperation(value = "传感器管理功能:编辑")
    public BusiResponse edit(@RequestBody @Validated(UpdateGroup.class) HfResSensor hfResSensor) {

        // 判断设备编号是否重复
        QueryWrapper<HfResSensor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(HfResSensor::getDelFlag, 1).ne(HfResSensor::getId, hfResSensor.getId());
        String sensorCode = hfResSensor.getSensorCode();
        queryWrapper.eq("sensor_code", sensorCode);
        int count = hfResSensorService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("编码%s已经存在！", hfResSensor.getSensorCode()));
        }
        hfResSensorService.updateById(hfResSensor);

        autoLogUtils.modifyLog("环境试验-传感器台账", String.format("编辑传感器:【%s】", sensorCode));
        return BusiResponse.ok("编辑成功！");
    }

    @PostMapping(value = "/editEnable")
    @ApiOperation(value = "传感器管理功能:编辑")
    public BusiResponse editEnable(@RequestBody HfResSensor hfResSensor) {
        hfResSensorService.updateById(hfResSensor);
        return BusiResponse.ok("编辑成功！");
    }

    @GetMapping("/queryById")
    @ApiOperation(value = "传感器管理功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(name = "id") String id) {
        HfResSensor resSensor = hfResSensorService.getById(id);
        Assert.notNull(resSensor, "数据不存在!");
        // 查询转换附件
        return BusiResponse.OK(resSensor);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "传感器管理功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        List<HfResSensor> sensorList = hfResSensorService.listByIds(idList);
        hfResSensorService.removeByIds(idList);
        String sensorNames = sensorList.stream()
                .map(HfResSensor::getSensorCode)
                .distinct()
                .collect(Collectors.joining(","));

        autoLogUtils.deleteLog("环境试验-传感器台账", String.format("删除了传感器:【%s】", sensorNames));
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "传感器管理功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error("参数有误！");
        }
        BusiResponse export = hfResSensorService.exportExcel(pageInfo);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("传感器信息.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);


            autoLogUtils.exportLog("环境试验-传感器台账", "传感器台账导出");
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "传感器管理功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                autoLogUtils.importLog("环境试验-传感器台账", "传感器台账导入");
                return hfResSensorService.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }

}